<?php
namespace App\Http\Controllers\Admin;

use App\Service\Admin\TmpService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;
use ZipArchive as Zip;

class TmpController extends BaseController
{
    //模板项目库

    public function __construct(TmpService $service)
    {
        $this->db = $service;
    }

    //列表
    public function getIndex(Request $request)
    {
//        $token = $request->post('token', '');
//        $uid = $this->db->getUidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '没有登录');
//        }
        $res = $this->db->getIndex();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //详情
    public function getOne(Request $request)
    {
        $item_id = $request->post('item_id', 0);
        $res = $this->db->getOne($item_id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //上传前台ZIP压缩包
    public function uploadFront(Request $request)
    {
//        $token = $request->post('token', '');
//        $uid = $this->db->getUidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '没有登录');
//        }
        $pas['type'] = $request->post('type', 1); //项目类型
        $pas['title'] = $request->post('title', ''); //项目名称
        $is_print = $request->post('is_print', 0); //是否打印：0不打印，1要打印
        if ($pas['type'] != 1) {
            return $this->toJson(-2, '目前只有能网站');
        }
        $resUpload = Upload::uploadItem($request, 'zip');
        if ($resUpload['code']<0 && $is_print) {
            return redirect('/test/item_upload.html?errFront=upload false');
        }
        if ($resUpload['code'] < 0) {
            return $this->toJson(-2, $resUpload['msg']);
        }
        $fs['fname'] = $resUpload['data']['origin'];
        $fs['forigin'] = $resUpload['data']['forigin'];
        $fs['folder'] = $resUpload['data']['folder'];
        $fs['fpath'] = $resUpload['data']['fpath'];
        $origins = explode('.', $fs['fname']);
        $resFile = $this->db->itemAdd($fs, $pas); //保存文件
        if ($resFile['code']<0 && $is_print) {
            return redirect('/test/item_upload.html?errFront=save false');
        }
        if ($resFile['code'] < 0) {
            return $this->toJson(-1, $resFile['msg']);
        }
        $itemId = $resFile['data']['item_id'];
        $itemSerial = $resFile['data']['serial'];
        //解压缩
        $zip = new Zip();
        $resZip = $zip->open($fs['fpath']);
        if ($resZip!=true && $is_print) {
            return redirect('/test/item_upload.html?errFront=unzip false');
        }
        if (!is_bool($resZip) || $resZip != true) {
            return $this->toJson(-2, '解压缩失败，错误代码：'.$resZip);
        }
        $zip->extractTo($fs['folder'].$fs['forigin']);
        $zip->close();
//        $dirs = scandir($fs['folder'].$fs['forigin']);
//        //处理多级空目录
//        if (count($dirs)<=3 && $dirs[2] == $origins[0]) {
//            $sourceDir = env('ITEM_PATH').'public/'.$fs['folder'].$fs['forigin'].'/'.$dirs[2];
//            $midDir = env('ITEM_PATH').'public/'.$fs['folder'].time();
//            $targetDir = env('ITEM_PATH').'public/'.$fs['folder'].$fs['forigin'];
//            if (env('OS') == 'linux') {
//                exec("mv $sourceDir $targetDir");
//            } else {
//                exec("move $sourceDir $midDir"); //重命名
//                rmdir($fs['folder'].$fs['forigin']); //删除
//                exec("move $midDir $targetDir"); //重命名
//            }
//        }
        //复制到项目目录
        $targetDir = $fs['folder'].$fs['forigin'];
        //$itemDir = 'ai_items/'.$fs['forigin'];
        if (!file_exists('ai_items/'.$itemSerial)) {
            mkdir('ai_items/'.$itemSerial, 0777);
        }
        $itemDir = 'ai_items/'.$itemSerial.'/front_view';
        $this->copydir($targetDir, $itemDir);
        if (!file_exists($itemDir) && $is_print) {
            return redirect('/test/item_upload.html?errFront=item dir false');
        }
        if (!file_exists($itemDir)) {
            return $this->toJson(-2, '项目目录失败');
        }
        //保存文件树地址
        $frontApi = $this->db->getDocList($itemId, 1);
        $adminApi = $this->db->getDocList($itemId, 2);
        $treeArys = [
            'front_view' => $this->db->addPath($itemDir, $itemId, 2),
            'front_api' => $frontApi['code']==0 ? $frontApi['data'] : [],
            'admin_view' => [],
            'admin_api' => $adminApi['code']==0 ? $adminApi['data'] : [],
        ];
        $itemArys = [
            'itemId' => $itemId,
            'itemName' => $origins[0],
            'treeList' => $treeArys,
        ];
        if ($is_print) {
            return redirect('/test/item_upload.html?errFront=success');
        }
        return $this->toJson(0, '', $itemArys);
    }

    //上传后台ZIP压缩包
    public function uploadAdmin(Request $request)
    {
//        $token = $request->post('token', '');
//        $uid = $this->db->getUidByToken($token);
//        if (!$uid) {
//            return $this->toJson(-2, '没有登录');
//        }
        $itemId = $request->post('item_id', 0); //项目ID
        $is_print = $request->post('is_print', 0); //是否打印：0不打印，1要打印
        $itemOne = $this->db->getOne($itemId);
        if ($itemOne['code']<0 && $is_print) {
            ddd($itemOne);
        }
        if ($itemOne['code'] < 0) {
            return $this->toJson(-2, $itemOne['msg']);
        }
        $resUpload = Upload::uploadItem($request, 'zip');
        if ($resUpload['code']<0 && $is_print) {
            return redirect('/test/item_upload.html?errAdmin=upload false');
        }
        if ($resUpload['code'] < 0) {
            return $this->toJson(-2, $resUpload['msg']);
        }
        $fs['fname'] = $resUpload['data']['origin'];
        $fs['forigin'] = $resUpload['data']['forigin'];
        $fs['folder'] = $resUpload['data']['folder'];
        $fs['fpath'] = $resUpload['data']['fpath'];
        $origins = explode('.', $fs['fname']);
        $resFile = $this->db->itemModify($itemId, $fs); //保存文件
        if ($resFile['code']<0 && $is_print) {
            return redirect('/test/item_upload.html?errAdmin=save false');
        }
        if ($resFile['code'] < 0) {
            return $this->toJson(-1, $resFile['msg']);
        }
        //解压缩
        $zip = new Zip();
        $resZip = $zip->open($fs['fpath']);
        if ($resZip!=true && $is_print) {
            return redirect('/test/item_upload.html?errAdmin=unzip false');
        }
        if (!is_bool($resZip) || $resZip != true) {
            return $this->toJson(-2, '解压缩失败，错误代码：'.$resZip);
        }
        $zip->extractTo($fs['folder'].$fs['forigin']);
        $zip->close();
        //复制到项目目录
        $targetDir = $fs['folder'].$fs['forigin'];
        $itemDir = 'ai_items/'.$itemOne['data']['serial'].'/admin_view';
        $this->copydir($targetDir, $itemDir);
        if (!file_exists($itemDir) && $is_print) {
            return redirect('/test/item_upload.html?errAdmin=item dir false');
        }
        if (!file_exists($itemDir)) {
            return $this->toJson(-2, '项目目录失败');
        }
        //保存文件树地址
        $frontApi = $this->db->getDocList($itemId, 1);
        $adminApi = $this->db->getDocList($itemId, 2);
        $treeArys = [
            'front_view' => $this->db->getTree($itemId, 2),
            'front_api' => $frontApi['code']==0 ? $frontApi['data'] : [],
            'admin_view' => $this->db->addPath($itemDir, $itemId, 1),
            'admin_api' => $adminApi['code']==0 ? $adminApi['data'] : [],
        ];
        $itemArys = [
            'itemId' => $itemId,
            'itemName' => $origins[0],
            'treeList' => $treeArys,
        ];
        if ($is_print) {
            return redirect('/test/item_upload.html?errAdmin=success');
        }
        return $this->toJson(0, '', $itemArys);
    }

    //复制目录
    public function copydir($src, $dst)
    {
        if (!file_exists($dst)) mkdir($dst);
        $handle = opendir($src);
        while (($item=readdir($handle)) !== false) {
            if ($item == '.' || $item == '..') continue;
            $_src = $src.'/'.$item;
            $_dst = $dst.'/'.$item;
            if (is_file($_src)) copy($_src, $_dst);
            if (is_dir($_src)) $this->copydir($_src, $_dst);
        }
        closedir($handle);
    }

    //读取文件内容
    public function fileRead(Request $request)
    {
        $fid = $request->post('fid', 0);
        $res = $this->db->getFileOne($fid);
        if (empty($res)) {
            return $this->toJson(-2, '没有文件地址');
        }
        if (!file_exists($res['url'])) {
            return $this->toJson(-2, '没有文件');
        }
        $fdetail = file_get_contents($res['url']);
        return $this->toJson(0, '', $fdetail);
    }

//    //导出
//    public function export(Request $request)
//    {
//        $item_id = $request->post('item_id', 0);
//        $res = $this->db->getOne($item_id);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        $fname = $res['data']['en'];
//        $sourceDir = 'ai_items/'.$res['data']['en'];
//        if (!file_exists($sourceDir)) {
//            return $this->toJson(-2, '文件不存在');
//        }
//        //压缩
//        $randTime = time();
//        if (!class_exists('ZipArchive')) {
//            return $this->toJson(-2, '压缩程序没有安装');
//        }
//        $targetDir = env('ITEM_PATH').'public/'.$sourceDir.'_'.$randTime.'.zip';
//        $zip = new Zip();
//        if (!$zip->open($targetDir, Zip::CREATE | Zip::OVERWRITE)) {
//            return $this->toJson(-2, "无法打开压缩包 $targetDir");
//        }
//        $this->addFileToZip($sourceDir, $sourceDir, $zip);
//        $zip->close();
//        $fpath = env('DOMAIN').'/api/admin/item/down?zipName='.$fname.'_'.$randTime.'.zip';
//        return $this->toJson(0, '', $fpath);
//    }
//
//    /**
//     * 压缩目录
//     * @param string $path 电脑绝对地址
//     * @param string $fpath 项目相对地址
//     * @param object $zip 压缩对象
//     */
//    public function addFileToZip($path, $fpath, $zip)
//    {
//        $handle = opendir($path);
//        while (($fname=readdir($handle)) !== false) {
//            if (!in_array($fname, ['.', '..'])) {
//                if (is_dir($path.'/'.$fname)) {
//                    $this->addFileToZip($path.'/'.$fname, $fpath, $zip);
//                } else {
//                    $zip->addFile($path.'/'.$fname, $fpath.'/'.$fname);
//                }
//            }
//        }
//        @closedir();
//    }
//
//    //下载zip
//    public function down(Request $request)
//    {
//        $zipName = $request->get('zipName', '');
//        header('Content-Type: application/zip');
//        header('Content-disposition: attachment; filename=' . basename($zipName));
//        header('Content-Length: '. filesize($zipName));
//        readfile($zipName);
//    }
}